package com.wzq.controller.pc;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.wzq.controller.admin.GetSome;
import com.wzq.dao.pojo.Code;
import com.wzq.dao.pojo.Like;
import com.wzq.dao.pojo.Result;
import com.wzq.service.ILikeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author yzc
 * @since 2022-08-31
 */
@RestController
@RequestMapping("/PC/like")
public class PCLikeController extends GetSome {

    @Autowired
    private ILikeService iLikeService;

    //   添加
    @PostMapping
    public Result save(@RequestBody Like like) {
        boolean flag = iLikeService.save(like);
        return new Result(flag ? Code.SAVE_OK : Code.SAVE_ERR, flag);
    }

    //查询是否点赞
    @PostMapping("/islike")
    public Result islike(@RequestBody Like like) {
        LambdaQueryWrapper<Like> lqw = new LambdaQueryWrapper<>();
        lqw.eq(Like::getP_id, like.getP_id());
        lqw.eq(Like::getW_id, like.getW_id());
        Like like1 = iLikeService.getOne(lqw);
        if (like1 == null) {
            return new Result(Code.SAVE_OK, "点赞成功");
        } else {
            return new Result(Code.SAVE_ERR, "取消点赞");
        }
    }


    //   修改
    @PutMapping
    public Result update(@RequestBody Like like) {
        boolean flag = iLikeService.updateById(like);
        return new Result(flag ? Code.UPDATE_OK : Code.UPDATE_ERR, flag);
    }

    //    删除点赞
    @PostMapping("/like")
    public Result deleteById(@RequestBody Like like) {
        LambdaQueryWrapper<Like> lqw = new LambdaQueryWrapper<>();
        lqw.eq(Like::getP_id, like.getP_id());
        lqw.eq(Like::getW_id, like.getW_id());
        int flag = 0;
        if (iLikeService.getOne(lqw) == null) {
            if (iLikeService.save(like)) {
                iProjectService.updateLove( 1,like.getP_id());
                flag = 1;
            }
        } else {
            if (iLikeService.remove(lqw)) {
                iProjectService.updateLove( -1,like.getP_id());
                flag = 2;
            }
        }

        return new Result(flag > 0 ? Code.DELETE_OK : Code.DELETE_ERR, flag);
    }

    //    获得id对应用户信息
    @GetMapping("/{id}")
    public Result getById(@PathVariable Integer id) {
        Like like = iLikeService.getById(id);
        Integer code = like != null ? Code.GET_OK : Code.GET_ERR;
        String msg = like != null ? "" : "数据查询失败，请重试！";
        return new Result(code, like, msg);
    }

    //     获得所有用户信息
    @GetMapping
    public Result getAll() {
        List<Like> list = iLikeService.list();
        System.out.println(list);
        Integer code = list != null ? Code.GET_OK : Code.GET_ERR;
        String msg = list != null ? "" : "数据查询失败，请重试！";
        return new Result(code, list, msg);
    }

}
